import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Card, Icon, Upload, message, Modal,
} from 'antd';
import globalConstant from '../../utils/globalConstant';


const FormItem = Form.Item;


@connect(state => ({
  general: state.general,
}))
@Form.create()
export default class AddMaster extends PureComponent {
  state ={
    uploadFileLength: [],
    previewVisible: false,
    previewImage: '',
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'general/getDistrictList',
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log(values);
        this.props.form.resetFields();
        this.props.form.setFieldsValue({ upload: null });
        this.setState({
          uploadFileLength: [],
        });
        const fileListArray = [];
        fileListArray.push(values.upload && values.upload.map(item => (
          item.response && item.response.data.map(items => items.fileUrl))));
        console.log(fileListArray);
        const serviceArray = [];
        values.serviceAddres.map((item) => {
          return serviceArray.push({ districtId: item });
        });
        this.props.dispatch({
          type: 'masterManage/addMaster',
          payload: {
            idcardPhotoFront: fileListArray[0][0].toString() || null,
            idcardPhotoSide: fileListArray[0][1].toString() || null,
            loginName: values.userName,
            loginPassword: values.userPwd,
            userName: values.name,
            userMobile: values.phoneNumber,
            userIdcard: values.Identity,
            serviceAddrs: serviceArray,
            userEmail: values.email,
          },
          callback: () => {
            this.props.handleAddModal();
          },
        });
      }
    });
  }
  normFile = (e) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    this.setState({
      uploadFileLength: e.fileList,
    });
    return e && e.fileList;
  }
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleCancel=() => {
    this.setState({
      previewVisible: false,
    });
  }
  render() {
    const { general: { districtList } } = this.props;
    const { uploadFileLength, previewImage, previewVisible } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const children = [];
    districtList.map(item => (
      children.push(
        <Select.Option
          key={item.id}
          value={item.id}
        >{item.districtName}
        </Select.Option>)
    ));
    const updateProps = {
      name: 'file',
      action: globalConstant.fileUploadURL,
      headers: {
        authorization: 'authorization-text',
      },
      listType: 'picture-card',
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div >点击选择</div>
      </div>
    );
    return (
      <Card bordered={false}>
        <Form
          onSubmit={this.handleSubmit}
          style={{ marginTop: 8 }}
        >
          <FormItem
            {...formItemLayout}
            label="登录账号"
          >
            {getFieldDecorator('userName', {
              rules: [{
                required: true, message: '请输入登录账号',
              }],
            })(
              <Input placeholder="请输入登录账号" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="登录密码"
          >
            {getFieldDecorator('userPwd', {
              rules: [{
                required: true, message: '请输入登录密码',
              }],
            })(
              <Input placeholder="请输入登录密码" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="师傅名字"
          >
            {getFieldDecorator('name', {
              rules: [{
                required: true, message: '请输入姓名',
              }],
            })(
              <Input placeholder="请输入姓名" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="联系电话"
          >
            {getFieldDecorator('phoneNumber', {
              rules: [{
                required: true, message: '请输入联系电话',
              }],
            })(
              <Input placeholder="请输入联系电话" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="电子邮箱"
          >
            {getFieldDecorator('email', {
              rules: [{
              }],
            })(
              <Input placeholder="请输入电子邮箱" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="身份证号"
          >
            {getFieldDecorator('Identity', {
              rules: [{
                required: true, message: '请输入身份证号',
              }],
            })(
              <Input placeholder="请输入身份证号" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="服务区域"
          >
            {getFieldDecorator('serviceAddres', {
              rules: [
                {
                  type: 'array',
                },
                {
                  required: true, message: '请输入身份证号',
                }],
            })(
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择服务区域"
              >
                {children}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="上传身份证"
          >
            {getFieldDecorator('upload', {
              valuePropName: 'fileList',
              getValueFromEvent: this.normFile,
            })(
              <Upload {...updateProps} onPreview={this.handlePreview}>
                {uploadFileLength.length >= 2 ? null : uploadButton}
              </Upload>
            )}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </FormItem>
        </Form>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    );
  }
}
